package conf

import (
	"github.com/spf13/viper"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

type Conf struct {
	*viper.Viper
}

/**
 * 设置日志配置并返回实例化对象
 * t 日志文件类型 yaml（yml） 、ini 、toml、dotenv（env）、json、hcl、properties（props、prop）
 * path ... 文件或目录路径
 */
func SGetConfigs(t string, path ...string) (*Conf, error) {
	conf := viper.New()
	if len(path) == 0 {
		return &Conf{conf}, nil
	}
	if t == "" {
		t = strings.Trim(filepath.Ext(path[0]), ".")
	}
	if t != "" {
		conf.SetConfigType(t)
	}

	for _, p := range path {
		f, err := os.Stat(p)
		if err != nil {
			return nil, err
		}
		if f.IsDir() {
			files, err := getDirFiles(p)
			if err != nil {
				continue
			}
			for _, file := range files {
				dir, filename := filepath.Split(file)
				conf.SetConfigName(filename)
				conf.AddConfigPath(dir)
			}
		} else {
			dir, filename := filepath.Split(p)
			conf.SetConfigName(filename)
			conf.AddConfigPath(dir)
		}
	}

	err := conf.ReadInConfig()
	if _, ok := err.(viper.ConfigFileNotFoundError); err != nil && !ok {
		return nil, err
	}
	return &Conf{conf}, nil
}

func getDirFiles(dir string) ([]string, error) {
	files, err := ioutil.ReadDir(dir)
	if err != nil || len(files) == 0 {
		return nil, err
	}
	var filePaths []string
	for _, file := range files {
		filePaths = append(filePaths, filepath.Join(dir, file.Name()))
	}
	return filePaths, nil
}
